﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using DataAccess;

namespace Controller
{
    public class DeliveryController:ControllerBase
    {
        public void addDelivery(int stockOutId, int stockItemId, int qty, int custPoItemId)
        {
            Delivery delivery = new Delivery();
            delivery.StockOutId = stockOutId;
            delivery.StockItemId = stockItemId;
            delivery.Qty = qty;
            delivery.CustPOItemId = custPoItemId;
            delivery.Remark = "";
            Sdc.Deliveries.InsertOnSubmit(delivery);
            Sdc.SubmitChanges();
        }



        public IList<DeliveryEntity> FindDeliveryByInvoiceId(int customerInvoiceId)
        {
            CustInvoice custInvoice = (from c in Sdc.CustInvoices
                                       where c.Id == customerInvoiceId
                                       select c).SingleOrDefault();
            IList<Delivery> deliveries = (from d in Sdc.Deliveries
                                          where d.StockOutId == custInvoice.StockOutId
                                       select d).ToList();
            IList<DeliveryEntity> deliveryEntities = new List<DeliveryEntity>();
            foreach (Delivery delivery in deliveries)
            {
                DeliveryEntity deliveryEntity= TransformDeliveryToDeliveryEntity(delivery);
                deliveryEntities.Add(deliveryEntity);
            }
            return deliveryEntities;
        }

        public static DeliveryEntity TransformDeliveryToDeliveryEntity(Delivery delivery)
        {
            DeliveryEntity deliveryEntity = new DeliveryEntity();
            deliveryEntity.ProductId = delivery.CustPOItem.Product.Id;
            deliveryEntity.ProductNo = delivery.CustPOItem.Product.No;
            deliveryEntity.ProductName = delivery.CustPOItem.Product.Name;
            deliveryEntity.BatchNo = delivery.StockItem.BatchNo;

            deliveryEntity.InvoiceNo = (delivery.StockOut.CustInvoices.FirstOrDefault() ?? new CustInvoice(){No = "",}).No;

            deliveryEntity.Quantity = delivery.Qty;
            deliveryEntity.PoId = delivery.CustPOItem.CustPO.Id;
            deliveryEntity.PoNo = delivery.CustPOItem.CustPO.No;
            deliveryEntity.Revision = delivery.CustPOItem.Product.Revision;
            deliveryEntity.Customer = delivery.CustPOItem.CustPO.Customer.Name;
            deliveryEntity.Lot = delivery.CustPOItem.Lot;
            deliveryEntity.RequestQty = delivery.CustPOItem.RequestQty;
            deliveryEntity.Remark = delivery.Remark;

            return deliveryEntity;
        }
    }
}
